package com.lagou.service.impl;

import com.lagou.dao.TokenDao;
import com.lagou.dao.UserDao;
import com.lagou.pojo.Token;
import com.lagou.pojo.User;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenDao tokenDao;

    @Override
    public User addUser(String email, String password) {

        User user = new User();
        user.setEmail(email);
        user.setPassword(password);

        User save = userDao.save(user);

        return save;
    }

    @Override
    public User findUser(String email) {

        User user = new User();
        user.setEmail(email);

        Example<User> example = Example.of(user);

        Optional<User> one = userDao.findOne(example);

        user = one.isPresent() ? one.get(): null;

        return user;
    }

    @Override
    public String fingEmailByToken(String tokenStr) {

        Token token = new Token();
        token.setToken(tokenStr);

        Example<Token> example = Example.of(token);

        Optional<Token> one = tokenDao.findOne(example);

        token = one.isPresent() ? one.get(): null;

        if(token != null){
            return token.getEmail();
        }

        return null;
    }

    @Override
    public Boolean validateUser(String email, String password) {

        User user = new User();
        user.setEmail(email);
        user.setPassword(password);

        Example<User> example = Example.of(user);
        Optional<User> one = userDao.findOne(example);

        if(!one.isPresent()){
            return false;
        }

        return true;
    }

    @Override
    public Token addToken(String email, String tokenStr) {

        Token token = new Token();
        token.setToken(tokenStr);
        token.setEmail(email);

        Token save = tokenDao.save(token);

        return save;
    }


}
